namespace cframework_xlua {
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using Newtonsoft.Json;
    using UnityEngine.AddressableAssets;
    using UnityEngine.Networking;

    public static class WhiteDeviceMgr
    {
        public enum Status
        {
            none,
            checking,
            check_failed,
            finish,
        }

        const string whiteDevicesFileName = "white_devices.txt";

        static string deviceId;
        static bool _isWhiteListDevice;

        static Status status;

        public static Status GetStatus()
        {
            return status;
        }

        public static bool isWhite()
        {
            return _isWhiteListDevice;
        }




        public static IEnumerator Check(string host, string id)
        {
            if (_isWhiteListDevice)
            {
                yield return true;
            }

            if (status != Status.none && status != Status.check_failed)
            {
                yield return false;
            }

            deviceId = id;
            status = Status.checking;

            string url = host + $"/{whiteDevicesFileName}?a=" + Random.Range(0, int.MaxValue);

            var request = UnityWebRequest.Get(url);
            request.timeout = UnityWebRequestManager.timeout;
            yield return request.SendWebRequest();

            _isWhiteListDevice = false;
            if (request.result == UnityWebRequest.Result.Success)
            {
                string str = System.Text.Encoding.UTF8.GetString(request.downloadHandler.data);
                System.IO.StringReader ss = new System.IO.StringReader(str);

                string line = null;
                while ((line = ss.ReadLine()) != null)
                {
                    string[] infos = line.Split(" ");

                    if (infos.Length < 2) continue;

                    bool enable = bool.Parse(infos[1]);
                    if (enable && deviceId == infos[0])
                    {
                        _isWhiteListDevice = true;
                    }
                }
            }

            status = Status.finish;

            yield return _isWhiteListDevice;
        }

        public static string ToInfoString()
        {
            string info = "";
        
            info += "deviceId: " + deviceId + "\n";
            info += "isWhiteListDevice: " + _isWhiteListDevice + "\n";
            info += "status: " + status + "\n";
            return info;
        }
    }
}